package com.blb.httptest;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 自定义的HTTP服务器
 */
public class MyHttpServer {

    public static final int PORT = 666;

    public static final String PATH = "D:\\home\\";

    public void start(){
        System.out.println("Http服务器启动了");
        try (ServerSocket serverSocket = new ServerSocket(PORT)){
            while(true){
                Socket socket = serverSocket.accept();
                StringBuilder request = new StringBuilder();
                //读取请求报文
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    request.append(line);
                    System.out.println(line);
                    if (line.length() == 0) {//""
                        break;
                    }
                }
                //截取请求报文中的url
                int start = request.indexOf(" ");
                String url = request.substring(start + 2, request.indexOf(" ", start + 1));
                System.out.println(url);
                //查找文件
                File file = new File(PATH + url);
                //读取文件内容
                StringBuilder html = new StringBuilder();
                try(BufferedReader reader = new BufferedReader(new FileReader(file))){
                    String s = null;
                    while((s = reader.readLine()) != null){
                        html.append(s + "\n");
                    }
                }catch (IOException ex){
                    ex.printStackTrace();
                }
                //拼接响应报文
                StringBuilder responseText = new StringBuilder();
                responseText.append("HTTP/1.1 200 OK\r\n");
                responseText.append("Content-Type: text/html;charset=UTF-8\r\n");
                responseText.append("\r\n");
                responseText.append(html);
                //向客户端发送响应报文
                OutputStream outputStream = socket.getOutputStream();
                outputStream.write(responseText.toString().getBytes());
                outputStream.flush();
                outputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new MyHttpServer().start();
    }
}
